package handlers

import (
	"encoding/json"

	"github.com/RuiGuangServer/config"
	"github.com/RuiGuangServer/global"
	"github.com/RuiGuangServer/logs"
	"github.com/RuiGuangServer/utils"
)

type Weather struct {
	Vis       int64  `json:"vis"`        // 数据类型，如 "VIS"
	CloudBase int64  `json:"cloud_base"` // 位置标识，如 "36R"
	Airdrome  string `json:"airdrome"`   // 机场代码，如 "ZGHA"
}

func HandleWeather(data []byte, logger *logs.AsyncLogger, dataer *logs.AsyncLogger) {
	dataer.Data("zstd压缩后的数据[Weather_receive]: %v", data)
	weatherjson, err := parsingWeather(data)
	if err != nil {
		logger.Warn("%v", err)
	}
	dataer.Data("zstd解压后的数据[Weather_receive]: %+v", weatherjson)

	//当云底高为0，代表无云，默认为3000，
	if weatherjson.CloudBase == 0 {
		weatherjson.CloudBase = 3000
	}
	wAP := weatherjson.Airdrome
	if wAP != config.Config.AirPort {
		logger.Info("Flight schedules for non %v airports", config.Config.AirPort)
		return
	}

	// 获取或创建机场状态
	state, _ := global.CurrentAirPortState.LoadOrStore(wAP, &global.AirPortState{
		AirPort: wAP,
		Vis:     0,
		Cloud:   0,
		Rvr:     0,
		Vis1A:   0,
		RWY:     "",
		Oper:    0,
	})

	currentState := state.(*global.AirPortState)

	isoper := false
	if weatherjson.Vis != currentState.Vis {
		currentState.Vis = weatherjson.Vis
		isoper = true
	}
	if currentState.Cloud != weatherjson.CloudBase {
		currentState.Cloud = weatherjson.CloudBase
		isoper = true
	}
	if isoper && currentState.Oper == 0 {
		currentState.Oper = 1
	}
}

// parsingAwos 解析气象数据
func parsingWeather(data []byte) (Weather, error) {
	var weatherjson Weather
	jsonByte, err := utils.ZstdToJson(data)
	if err != nil {
		return weatherjson, err
	}
	// fmt.Printf("decompressed :%v\n", decompressed)
	if err := json.Unmarshal(jsonByte, &weatherjson); err != nil {
		return weatherjson, err
	}
	return weatherjson, nil
}
